<template>
  <div class="group-store">
    <div class="table-title">
      <!-- <el-select v-model="searchData.CategoryId" placeholder="请选择房型" @change="getpricePolicyList(searchData.CategoryId,'PolicyList')">
        <el-option :label="'全部房型'" :value="0"></el-option>
        <el-option v-for="m in HotelList" :label="m.Name" :value="m.Id" :key="m.Id"></el-option>
      </el-select>
      <el-select v-model="searchData.PolicyId" placeholder="请选择政策">
        <el-option :label="'全部政策'" :value="0"></el-option>
        <el-option v-for="m in PolicyList" :label="m.Name" :value="m.Id" :key="m.Id"></el-option>
      </el-select> -->
      <el-date-picker
        v-model="dateTime"
        type="daterange"
        :editable="false"
        :clearable="false"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        @change="getDate"
        :picker-options="pickerOptions">
      </el-date-picker>
      <el-button type="primary" @click="initList">查询</el-button>
      <el-button type="primary" @click="handleAdd" data-auth="store_price_bathmodify">批量修改价格</el-button>
    </div>
    <div class="table-content store-price">
      <table class="price-table" v-if="tableData.length>0">
        <tr>
          <th>
            <div>
              房型名称
            </div>
          </th>
          <th>
            <div>
              政策名称
            </div>
          </th>
          <th v-for="(m,index) in dateList">
            <div :class="{'weekend':getDays(index)===6||getDays(index)===0,
            'today':isToday(index)}">
              <template v-if="isToday(index)">今天--</template>
              {{$format('MM-dd',getFormatDay(index))}}--{{weekday[getFormatDay(index).getDay()]}}
            </div>
          </th>
        </tr>
        <tr v-for="(m,mindex) in tableData">
          <td>
            <div>
              {{m.CategoryName}}
            </div>
          </td>
          <td>
            <div>
              {{m.PolicyName}}
            </div>
          </td>
          <td v-for="(n,nindex) in dateList">
            <div class="set-price" @click="setPrice(m.PolicyList[nindex],m)" v-if="m.PolicyList[nindex].HasPrice">
              {{m.PolicyList[nindex].PriceAmount}}
            </div>
            <div class="" v-else>
              未设置
            </div>
          </td>
        </tr>
      </table>
    </div>
    <div class="table-page">

    </div>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="roomShow"
      width="350px"
      center>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
        <el-form-item label="价格：" prop="Amount">
          <el-input v-model="ruleForm.Amount"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="setOneprice('ruleForm')" data-auth="store_price_modify">保存</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="dialogTitle"
      :visible.sync="priceShow"
      width="750px"
      class="price-model"
      center>
      <el-form :model="priceForm" ref="priceForm" label-width="140px">
        <div class="price-title">设置统一价格</div>
				<div style="width:100%;">
          <el-form-item style="width:330px;display:inline-block" label="选择房型：" label-width="130px" prop="hotelId" :rules="{ required: true, message: '请选择房型', trigger: 'change' }">
            <el-select v-model="priceForm.hotelId" placeholder="请选择房型" @change="getpricePolicyList(priceForm.hotelId,'pricePolicyList')">
              <el-option v-for="m in priceHotelList" :label="m.Name" :value="m.Id" :key="m.Id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item style="width:330px;display:inline-block" label="选择政策：" label-width="130px" prop="Id" :rules="{ required: true, message: '请选择政策', trigger: 'change' }">
            <el-select v-model="priceForm.Id" placeholder="请选择政策" @change="getPrice">
              <el-option v-for="m in pricePolicyList" :label="m.PolicyName" :value="m.Id" :key="m.Id"></el-option>
            </el-select>
          </el-form-item>
					<el-form-item label="统一价格日期：" label-width="160px" prop="dateTime" :rules="{ required: true, message: '请选择日期', trigger: 'change' }">
						<el-date-picker
							v-model="priceForm.dateTime"
							type="daterange"
							:editable="false"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							:picker-options="pickerOptions"
						>
						</el-date-picker>
          </el-form-item>
				</div>
        <div class="month-price">
					<template v-for="(m,index) in priceForm.WeekPriceList">
						<el-form-item :label="m.dayName" :prop="'WeekPriceList.' + index + '.Price'" :rules="{ required: true, message: '价格不能为空', trigger: 'blur' }	">
	            <el-input v-model="m.Price"></el-input>
	          </el-form-item>
					</template>
        </div>
        <div class="price-title">设置特殊价格</div>
        <div class="spcial-price">
          <div class="btn" @click="priceForm.SpecialPriceList.push({dateTime:[],Price:''})">
            <i class="el-icon-plus"></i>
            <span icon="el-icon-plus">新增特殊价格</span>
          </div>
          <div class="spcial-form" v-for="(m,index) in priceForm.SpecialPriceList">
            <el-form-item label-width="0" :prop="'SpecialPriceList.' + index + '.dateTime'" :rules="{ required: true, message: '请选择日期', trigger: 'change' }">
              <el-date-picker
                v-model="m.dateTime"
                type="daterange"
								:editable="false"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
								:picker-options="SpecialpickerOptions">
              </el-date-picker>
            </el-form-item>
            <el-form-item label-width="0" :prop="'SpecialPriceList.' + index + '.Price'" :rules="{ required: true, message: '价格不能为空', trigger: 'blur' }	">
              <el-input width="150px" v-model="m.Price" placeholder="特殊价格"></el-input>
            </el-form-item>
            <div class="btn" @click="priceForm.SpecialPriceList.splice(index,1)">
              <i class="el-icon-minus"></i>
              <span icon="el-icon-plus">删除本条价格</span>
            </div>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addPrice('priceForm')" data-auth="room_price_modify">保存</el-button>
        <el-button @click="priceShow = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data () {
      var _this=this;
      return {
        SpecialpickerOptions: {
          disabledDate(time) {
            let start=(time.getTime() + 3600 * 1000 * 24 * 1)< Date.now();
            if(!_this.priceForm.dateTime){
              return start
            }else{
              let end=new Date(_this.priceForm.dateTime[1]).getTime() + 3600 * 1000 * 24 * 1;
              start=time.getTime()<new Date(_this.priceForm.dateTime[0]).getTime()
              return start||time>=end
            }
          }
        },
        pickerOptions: {
          disabledDate(time) {
            // return (time.getTime() + 3600 * 1000 * 24 * 1)< Date.now();
          }
        },
        dialogTitle:'',
        roomShow:false,
        dialogColTitle:'',
        roomColShow:false,
        tableData: [],
        searchData:{
          hotelId:JSON.parse(sessionStorage.getItem('nowmenu')).Id,
          beginDate:'',
          endDate:''
        },
        dateTime:[],
        dateList:[],
        pageTotal:0,
        ruleForm: {
        },
        colForm: {
          name: '',
          phone: '',
          city: '',
          address: '',
          resource:false
        },
        rules: {
          Amount: [
            { required: true, message: '请输入价格', trigger: 'blur' },
          ],
        },
        weekday:["周日","周一","周二","周三","周四","周五","周六"],
        priceShow:false,
        priceForm:{
          hotelId:'',
          policyId:'',
          dateTime:'',
          SpecialPriceList:[],
          WeekPriceList:[
            {DayOfWeek:0,dayName:'周一',Price:''},
            {DayOfWeek:1,dayName:'周二',Price:''},
            {DayOfWeek:2,dayName:'周三',Price:''},
            {DayOfWeek:3,dayName:'周四',Price:''},
            {DayOfWeek:4,dayName:'周五',Price:''},
            {DayOfWeek:5,dayName:'周六',Price:''},
            {DayOfWeek:6,dayName:'周日',Price:''}
          ]
        },
        HotelList:[],
        priceHotelList:[],
        pricePolicyList:[]
      }
    },
    mounted(){
      this.dateTime=[new Date(),new Date(new Date().getTime() + 3600 * 1000 * 24 * 30)];
      this.getDate(this.dateTime);
      this.dateList=this.getAlldate(this.searchData.beginDate,this.searchData.endDate);
      this.initList();
    },
    methods:{
      getDate(date){
        this.searchData.beginDate=this.$format('yyyy-MM-dd',new Date(date[0]))
        this.searchData.endDate=this.$format('yyyy-MM-dd',new Date(date[1]))
      },
      getAlldate(start,end){
        let bd = new Date(start),be = new Date(end);
        let bdTime = bd.getTime(), beTime = be.getTime(),timeDiff = beTime - bdTime;
        let dArr = [];
        for(var i=0; i<= timeDiff; i+=86400000){
          var ds = this.$format('yyyy-MM-dd',new Date(bdTime+i));
          dArr.push(ds)
        }
        return dArr
      },
      getDays(index){
        return new Date(new Date(this.searchData.beginDate).getTime() + 3600 * 1000 * 24 * index).getDay();
      },
      getFormatDay(index){
        return new Date(new Date(this.searchData.beginDate).getTime() + 3600 * 1000 * 24 * index);
      },
      isToday(index){
        return this.$format('MM-dd',new Date())===this.$format('MM-dd',this.getFormatDay(index));
      },
      initList(){
        this.roomShow=false;
        this.roomColShow=false;
        this.priceShow=false;
        this.getList();
      },
      getList(){
        this.$ajax.gethotelpricecalendar(this.searchData).then(res=>{
          if(res.Success){
            let data=[];
            _.map(res.Data,val=>{
              let rowspan=val.PriceList.length;
                  data.push({
                    PolicyId:val.PolicyId,
                    PolicyName:val.PolicyName,
                    CategoryName:val.RoomCategoryName,
                    PolicyList:val.PriceList,
                    rowspan:rowspan
                  })
            })
            this.$nextTick(()=>{
              this.dateList=this.getAlldate(this.searchData.beginDate,this.searchData.endDate);
              this.$set(this,'tableData',data);
            })
          }
        })
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg'||file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
          return
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
          return
        }
        let reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onloadend = ()=>{
          file.url = reader.result;
          this.fileList.push(file);
          // this.$refs['ruleForm'].validateField('imageUrl');
        }
        return false;
      },
      resetForm(formName) {
        if(!this.$refs[formName]){return};
        this.$refs[formName].resetFields();
      },
      handleAdd(index, row) {
        this.dialogTitle='批量修改价格';
        this.priceForm={
          Id:'',
          hotelId:'',
          policyId:'',
          dateTime:'',
          SpecialPriceList:[],
          WeekPriceList:[
            {DayOfWeek:0,dayName:'周一',Price:''},
            {DayOfWeek:1,dayName:'周二',Price:''},
            {DayOfWeek:2,dayName:'周三',Price:''},
            {DayOfWeek:3,dayName:'周四',Price:''},
            {DayOfWeek:4,dayName:'周五',Price:''},
            {DayOfWeek:5,dayName:'周六',Price:''},
            {DayOfWeek:6,dayName:'周日',Price:''}
          ]
        };
        this.resetForm('priceForm');
        this.getpriceHotelList(this.searchData.hotelId,'priceHotelList');
        this.priceShow=true;
      },
      getPrice(val){
        _.map(this.pricePolicyList,row=>{
          if(row.Id===val){
            this.priceForm.dateTime=[row.StartDate,row.EndDate];
            this.priceForm.WeekPriceList=[
              {DayOfWeek:0,dayName:'周一',Price:row.MondayPrice},
              {DayOfWeek:1,dayName:'周二',Price:row.TuesdayPrice},
              {DayOfWeek:2,dayName:'周三',Price:row.WednesdayPrice},
              {DayOfWeek:3,dayName:'周四',Price:row.ThursdayPrice},
              {DayOfWeek:4,dayName:'周五',Price:row.FridayPrice},
              {DayOfWeek:5,dayName:'周六',Price:row.SaturdayPrice},
              {DayOfWeek:6,dayName:'周日',Price:row.SundayPrice}
            ]
          }
        })
      },
      addPrice(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let data={
              Id:this.priceForm.Id,
              RoomCategoryId:this.priceForm.hotelId,
              MondayPrice:this.priceForm.WeekPriceList[0].Price,
              TuesdayPrice:this.priceForm.WeekPriceList[1].Price,
              WednesdayPrice:this.priceForm.WeekPriceList[2].Price,
              ThursdayPrice:this.priceForm.WeekPriceList[3].Price,
              FridayPrice:this.priceForm.WeekPriceList[4].Price,
              SaturdayPrice:this.priceForm.WeekPriceList[5].Price,
              SundayPrice:this.priceForm.WeekPriceList[6].Price,
              StartDate:this.$format('yyyy-MM-dd',new Date(this.priceForm.dateTime[0])),
              EndDate:this.$format('yyyy-MM-dd',new Date(this.priceForm.dateTime[1])),
              SpecialPriceList:this.priceForm.SpecialPriceList
            };
            _.map(data.SpecialPriceList,(val)=>{
              val.StartDate=this.$format('yyyy-MM-dd',new Date(val.dateTime[0]));
              val.EndDate=this.$format('yyyy-MM-dd',new Date(val.dateTime[1]));
            })

            this.$ajax.savepolicy(data).then(res=>{
              if(res.Success){
                this.$message.success(this.dialogTitle+'成功!');
                this.$refs[formName].resetFields();
                this.initList();
              }
            })
          } else {
            return false;
          }
        });
      },
      setPrice(data,{PolicyId}) {
        if(!data){
          this.$message({
            type: 'warning',
            message: '请在批量设置里初始化价格！'
          });
          return
        }else{
          this.dialogTitle='修改价格';
          this.resetForm('ruleForm');
          this.ruleForm={
            PolicyId:PolicyId,
            Amount:data.PriceAmount||0,
            SpecialDate:data.PriceDate,
          }
          this.roomShow=true;
        }
      },
      getpriceHotelList(id,type){
        this.$ajax.GetRoomCategoryByHotelId({hotelId:id}).then(res=>{
          if(res.Success){
            this[type]=res.Data;
          }
        })
      },
      getpricePolicyList(id,type){
        this.priceForm.Id='';
        this.priceForm.WeekPriceList=[
          {DayOfWeek:0,dayName:'周一',Price:''},
          {DayOfWeek:1,dayName:'周二',Price:''},
          {DayOfWeek:2,dayName:'周三',Price:''},
          {DayOfWeek:3,dayName:'周四',Price:''},
          {DayOfWeek:4,dayName:'周五',Price:''},
          {DayOfWeek:5,dayName:'周六',Price:''},
          {DayOfWeek:6,dayName:'周日',Price:''}
        ]
        this.$ajax.getpolicylist({roomCategoryId:id}).then(res=>{
          if(res.Success){
            this[type]=res.Data;
          }
        })
      },
      setOneprice(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$ajax.setspecialprice(this.ruleForm).then(res=>{
              if(res.Success){
                this.$message.success(this.dialogTitle+'成功!');
                this.$refs[formName].resetFields();
                this.initList();
              }
            })
          } else {
            return false;
          }
        });
      }
    }
  }
</script>
